package jhunter.service;

import groovy.json.JsonBuilder;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import jhunter.dao.DaoFactory;
import jhunter.dao.DataAccess;
import jhunter.dao.bo.BaseObject;

import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.fastjson.JSON;

public class BaseModuleService implements ModuleService {

	private DaoFactory daoFactory;

	private TransactionTemplate transactionTemplate;

	public DaoFactory getDaoFactory() {
		return daoFactory;
	}

	public void setDaoFactory(DaoFactory daoFactory) {
		this.daoFactory = daoFactory;
	}

	public TransactionTemplate getTransactionTemplate() {
		return transactionTemplate;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	public DataAccess getDAO(String entityId) {
		return daoFactory.getDao(entityId);
	}

	public String json(Object value) {
		return JSON.toJSONString(value);
//		return new JsonBuilder(value).toPrettyString();
	}

	public List<Map<String, Object>> tree(List<BaseObject> values, Map<String, String> keyMapping) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (values != null) {
			for (int i = 0; i < values.size(); i++) {
				BaseObject value = values.get(i);
				Map<String, Object> map = new LinkedHashMap<String, Object>();
				for (String key : keyMapping.keySet()) {
					map.put(key, value.get(keyMapping.get(key)));
				}
				if(i == 0) {
					map.put("open", true);
				}
				list.add(map);
			}
		}
		return list;
	}

}
